<?php
/**
 * 关注商铺或商品
 * Created by PhpStorm.
 * User: Jmashimaro
 * Date: 2015/1/19
 * Time: 16:05
 */
class FavoriteApp extends FrontendApp {

    /**
     * 关注商铺列表
     * @author jiayanxiu
     * @date 2015/02/04
     */
    public function storeList() {
        $config = require ROOT_PATH.'/data/config.qiniu.php';
        $method = strtoupper($_SERVER['REQUEST_METHOD']);
        if ($method != 'GET') {
            $this->ajax_return(FLAG_ERROR, '非法的请求！');
        }
        //检测用户是否登陆
        $user_id = $this->checkLogin();
        if (!$user_id) {
            $this->ajax_return(FLAG_ERROR, '请您进行登陆！');
        }
        $model = m('store');
        $sql = 'SELECT s.store_id,s.store_logo,s.store_name FROM '.DB_PREFIX.'collect c LEFT JOIN '.DB_PREFIX."store s ON c.item_id=s.store_id WHERE c.user_id={$user_id} AND c.type='store'";
        $data = $model->getAll($sql);
        if ($data) {
            foreach ($data as $key=>$val) {
                $val['store_logo'] = $val['store_logo'] ? $config['qiniu_url'].$val['store_logo'] : '';
                $data[$key] = $val;
            }
        }
        if ($data) {
            $this->ajax_return(FLAG_OK, '', $data);
        } else {
            $this->ajax_return(FLAG_ERROR, '没有更多数据！');
        }
    }

    /**
     * 添加关注商铺
     * @author jiayanxiu
     * @date 2015/01/19
     */
    public function addStore() {
        $method = strtoupper($_SERVER['REQUEST_METHOD']);
        if ($method != 'POST') {
            $this->ajax_return(FLAG_ERROR, '非法的请求！');
        }
        //检测用户是否登陆
        $user_id = $this->checkLogin();
        if (!$user_id) {
            $this->ajax_return(FLAG_ERROR, '请您进行登陆！');
        }
        $store_id = $this->get_gp('store_id', 'P');
        $store_id = $store_id ? intval($store_id) : 0;
        if (!$store_id) {
            $this->ajax_return(FLAG_ERROR, '不正确的商铺id！');
        }
        /* 验证要收藏的店铺是否存在 */
        $model_store = m('store');
        $store_info  = $model_store->get($store_id);
        if (!$store_info) {
            $this->ajax_return(FLAG_ERROR, '您关注的商铺不存在！');
        }

        /**开启事物**/
        $model_store->begin();

        /* 添加关注商铺 */
        $model_user = m('member');
        $sql = "SELECT user_id FROM ".DB_PREFIX."collect WHERE user_id={$user_id} AND item_id={$store_id} AND `type`='store'";
        $tmp = $model_store->getRow($sql);
        if ($tmp) {
            $this->ajax_return(FLAG_ERROR, '您已经关注了此商铺！');
        }
        $rs = $model_user->createRelation('collect_store', $user_id, array(
            $store_id   =>  array(
                'add_time'  =>  gmtime(),
            )
        ));
        if ($rs === false){
            $model_store->rollback();
            $this->ajax_return(FLAG_ERROR, '添加关注失败，请您重试！');
        }

        //更新收藏次数
        $flag = $model_store->update_collect_count($store_id);
        if ($flag === false) {
            $model_store->rollback();
            $this->ajax_return(FLAG_ERROR, '更新店铺收藏次数失败！，请您重试！');
        }
        $model_store->commit();//提交事物

        $this->ajax_return(FLAG_OK, '添加关注成功！');
    }

    /**
     * 取消商铺关注
     * @author jiayanxiu
     * @date 2015/01/20
     */
    public function delStore() {
        $method = strtoupper($_SERVER['REQUEST_METHOD']);
        if ($method != 'POST') {
            $this->ajax_return(FLAG_ERROR, '非法的请求！');
        }
        //检测用户是否登陆
        $user_id = $this->checkLogin();
        if (!$user_id) {
            $this->ajax_return(FLAG_ERROR, '请您进行登陆！');
        }

        $store_id = $this->get_gp('store_id', 'P');
        $store_id = $store_id ? intval($store_id) : 0;
        if (!$store_id) {
            $this->ajax_return(FLAG_ERROR, '不正确的商铺id！');
        }
        $ids = explode(',', $store_id);
        /* 解除“我”与店铺ID为$ids的收藏关系 */
        $model_user = m('member');
        $rs = $model_user->unlinkRelation('collect_store', $user_id, $ids);
        if ($rs === false){
            $this->ajax_return(FLAG_ERROR, '取消关注失败，请您重试！');
        } else {
            $this->ajax_return(FLAG_OK, '取消关注成功！');
        }

    }

    /**
     * 商品列表
     * @author jiayanxiu
     * @date 2015/02/04
     */
    public function goodsList() {
        $config = require ROOT_PATH.'/data/config.qiniu.php';
        $method = strtoupper($_SERVER['REQUEST_METHOD']);
        if ($method != 'GET') {
            $this->ajax_return(FLAG_ERROR, '非法的请求！');
        }
        //检测用户是否登陆
        $user_id = $this->checkLogin();
        if (!$user_id) {
            $this->ajax_return(FLAG_ERROR, '请您进行登陆！');
        }

        $sql = 'SELECT g.goods_id,g.goods_name,g.price,g.default_image FROM '.DB_PREFIX.'collect c
                LEFT JOIN '.DB_PREFIX."goods g ON c.item_id=g.goods_id WHERE c.user_id={$user_id} AND c.type='goods'
                AND g.if_examine = 1 AND g.if_finance = 1 AND g.if_show = 1 AND g.closed = 0";
        $model = m('goods');
        $data = $model->getAll($sql);
        if ($data) {
            foreach ($data as $key=>$val) {
                $val['default_image'] = $val['default_image'] ? $config['qiniu_url'].$val['default_image'] : '';
                $data[$key] = $val;
            }
        }
        $this->ajax_return(FLAG_OK, '', $data);
    }

    /**
     * 添加商品关注
     * @author jiayanxiu
     * @date 2015/04/01
     */
    public function addGoods() {
        $method = strtoupper($_SERVER['REQUEST_METHOD']);
        if ($method != 'POST') {
            $this->ajax_return(FLAG_ERROR, '非法的请求！');
        }
        //检测用户是否登陆
        $user_id = $this->checkLogin();
        if (!$user_id) {
            $this->ajax_return(FLAG_ERROR, '请您进行登陆！');
        }
        $goods_id = $this->get_gp('goods_id', 'P');
        $goods_id = $goods_id ? intval($goods_id) : 0;
        if (!$goods_id) {
            $this->ajax_return(FLAG_ERROR, '商品id不正确！');
        }
        /* 验证要收藏的商品是否存在 */
        $model_goods = m('goods');
        $goods_info  = $model_goods->get($goods_id);
        if (!$goods_info['goods_id']) {
            $this->ajax_return(FLAG_ERROR, '您关注的商品不存在！');
        }


        $model_user = m('member');
        //判断用户是否已经关注此商品
        $sql = "SELECT user_id FROM ".DB_PREFIX."collect WHERE user_id={$user_id} AND item_id={$goods_id} AND `type`='goods'";
        $tmp = $model_user->getRow($sql);
        if ($tmp) {
            $this->ajax_return(FLAG_ERROR, '您已经关注了此商品！');
        }
        /**添加关注**/
        $flag = $model_user->createRelation('collect_goods', $user_id, array(
            $goods_id   =>  array(
                'add_time'  =>  gmtime(),
            )
        ));
        if ($flag === false) {
            $model_goods->rollback();
            $this->ajax_return(FLAG_ERROR, '添加关注失败，请您重试！');
        }
        /* 更新被收藏次数 */
        $sql = "SELECT goods_id FROM ".DB_PREFIX."goods_statistics WHERE goods_id={$goods_id}";
        $row = $model_goods->getRow($sql);
        if ($row) {
            $sql = "UPDATE ".DB_PREFIX."goods_statistics SET collects=collects+1 WHERE goods_id={$goods_id}";
        } else {
            $sql = "INSERT INTO ".DB_PREFIX."goods_statistics (goods_id,collects) VALUES ({$goods_id},1)";
        }
        $rs = $model_goods->query($sql);
        if ($rs === false) {
            $model_goods->rollback();
            $this->ajax_return(FLAG_ERROR, '更新收藏次数失败，请您重试！');
        }

        /**提交事物**/
        $model_goods->commit();

        $this->ajax_return(FLAG_OK, '添加关注成功！');
    }

    /**
     * 取消商品关注
     */
    public function delGoods() {
        $method = strtoupper($_SERVER['REQUEST_METHOD']);
        if ($method != 'POST') {
            $this->ajax_return(FLAG_ERROR, '非法的请求！');
        }
        //检测用户是否登陆
        $user_id = $this->checkLogin();
        if (!$user_id) {
            $this->ajax_return(FLAG_ERROR, '请您进行登陆！');
        }
        $goods_id = $this->get_gp('goods_id', 'P');
        $goods_id = $goods_id ? intval($goods_id) : 0;
        if (!$goods_id) {
            $this->ajax_return(FLAG_ERROR, '商品id不正确！');
        }
        $ids = explode(',', $goods_id);

        /* 解除“我”与商品ID为$ids的收藏关系 */
        $model_user = m('member');
        $model_goods = m('goods');
        /**开启事物**/
        $model_goods->begin();

        $rs = $model_user->unlinkRelation('collect_goods', $user_id, $ids);
        if ($rs === false) {
            $model_user->rollback();
            $this->ajax_return(FLAG_ERROR, '取消关注失败，请您重试！');
        }

        /* 更新被收藏次数 */
        foreach ($ids as $goods_id) {
            $sql = "UPDATE ".DB_PREFIX."goods_statistics SET collects=collects-1 WHERE goods_id={$goods_id}";
            $rs = $model_goods->query($sql);
            if ($rs === false) {
                $model_goods->rollback();
                $this->ajax_return(FLAG_ERROR, '更新收藏次数失败，请您重试！');
            }
        }
        /**提交事物**/
        $model_goods->commit();
        $this->ajax_return(FLAG_OK, '取消关注成功！');
    }


}